<template>
  <div class="art-class">
    <!-- 返回首页 -->
    <div class="back-home">
      <router-link to="/home" class="back-home-link">
        <el-icon><arrow-left /></el-icon> 返回首页
      </router-link>
    </div>

    <!-- 分类名称列表 -->
    <el-row>
      <el-col :span="24">
        <el-tabs v-model="activeColumn" @tab-click="handleTabClick">
          <el-tab-pane label="全部" name="0"></el-tab-pane>
          <el-tab-pane
            v-for="category in categories"
            :key="category.ColumnID"
            :label="category.ColumnName"
            :name="category.ColumnID.toString()"
          ></el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>

    <!-- 帖子列表 -->
    <el-row>
      <el-col :span="24">
        <div v-if="loading" class="loading">
          <el-icon class="is-loading"><loading /></el-icon>
          加载中...
        </div>
        <div v-else-if="currentPagePosts.length > 0" class="post-list-content">
          <div v-for="post in currentPagePosts" :key="post.PostID" class="content" @click="goToBokeInfo(post.PostID)">
            <h2 class="post-title">{{ post.PostTitle }}</h2>
            <p class="post-content">
              {{ post.PostContent.length > 40 ? post.PostContent.slice(0, 40) + '......' : post.PostContent }}
            </p>
            <p class="post-meta">
              <span><strong>发布者ID:</strong> {{ post.Post_UserID }}</span>
              <span><strong>发布时间:</strong> {{ post.Post_Date }}</span>
            </p>
          </div>
        </div>
        <div v-else class="no-data">暂无帖子</div>
      </el-col>
    </el-row>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="filteredPosts.length"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { ElTabs, ElTabPane, ElRow, ElCol, ElIcon, ElPagination } from 'element-plus';
import { Loading, ArrowLeft } from '@element-plus/icons-vue'; // 导入 ArrowLeft 图标
import instance from '../api/server';
import { useRouter } from 'vue-router'; // 导入 useRouter

export default {
  components: {
    ElTabs,
    ElTabPane,
    ElRow,
    ElCol,
    ElIcon,
    ElPagination,
    Loading,
    ArrowLeft, // 注册 ArrowLeft 图标
  },
  setup() {
    const activeColumn = ref('0'); // 默认选中的分类ID（0 表示全部）
    const posts = ref([]); // 所有博文数据
    const filteredPosts = ref([]); // 过滤后的博文数据
    const categories = ref([]); // 分类数据
    const loading = ref(false); // 加载状态
    const currentPage = ref(1); // 当前页码
    const pageSize = ref(3); // 每页显示的博文数量
    const router = useRouter(); // 使用 useRouter

    // 计算当前页的博文数据
    const currentPagePosts = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return filteredPosts.value.slice(start, end);
    });

    // 获取所有博文数据
    const getPosts = async () => {
      loading.value = true;
      try {
        const response = await instance.get('/myinfo/blog/getallpost');
        if (response.data.status === 0) {
          posts.value = response.data.data; // 赋值后端返回的博文数据
          filteredPosts.value = response.data.data; // 初始化过滤后的数据
        } else {
          console.error('获取博文失败:', response.data.message);
        }
      } catch (error) {
        console.error('获取博文数据失败:', error);
      } finally {
        loading.value = false;
      }
    };

    // 获取分类数据
    const getCategories = async () => {
      try {
        const response = await instance.get('/myinfo/blog/column');

        console.log(response.data.data);

        if (response.data.status === 0) {
          categories.value = response.data.data; // 赋值后端返回的分类数据
        } else {
          console.error('获取分类失败:', response.data.message);
        }
      } catch (error) {
        console.error('获取分类数据失败:', error);
      }
    };
 
    // 处理分页变化事件
    const handlePageChange = (page) => {
      currentPage.value = page;
    };

    // 处理分类点击事件
    const handleTabClick = async (tab) => {
      const categoryId = tab.props.name; // 获取点击的分类ID
      loading.value = true; // 显示加载状态

      console.log(categoryId);

      try {
        let response;
        if (categoryId === '0') {
          // 如果点击的是“全部”，获取所有帖子
          response = await instance.get('/myinfo/blog/getallpost');
        } else {
          // 否则根据分类ID获取对应分类的帖子
          response = await instance.get(`/myinfo/blog/getpostbycolumn/${categoryId}`);
        }

        if (response.data.status === 0) {
          filteredPosts.value = response.data.data; // 更新过滤后的帖子数据
        } else {
          filteredPosts.value = [];
          console.error('该分类无帖子:', response.data.message);
        }
      } catch (error) {
        console.error('获取帖子数据失败:', error);
      } finally {
        loading.value = false; // 隐藏加载状态
        currentPage.value = 1; // 重置当前页码为1
      }
    };

    // 跳转到 BokeInfo 页面
    const goToBokeInfo = (postId) => {
      router.push(`/bokeinfo/${postId}`);
    };

    // 组件挂载时加载博文数据和分类数据
    onMounted(() => {
      getPosts();
      getCategories();
    });

    return {
      activeColumn,
      posts,
      filteredPosts,
      categories,
      loading,
      currentPage,
      pageSize,
      currentPagePosts,
      handlePageChange,
      handleTabClick,
      goToBokeInfo, // 返回 goToBokeInfo 方法
    };
  },
};
</script>

<style src="../assets/style/BokeColumn.css" scoped>
</style>